package com.jhz.speedy.common.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.jhz.speedy.BuildConfig;
import com.jhz.speedy.component.application.MyApplication;
import com.jhz.speedy.component.control.MyControl;

import java.io.File;
import java.io.IOException;

/**
 * 文件工具
 * Created by JunHeZ on 2017/6/30.
 */
public class FileUtils {
    /**
     * APP文件保存主路径
     */
    private static String APP_FILE_SAVE_ROOT_DRI;

    /**
     * 获取或创建，根目录下的子文件夹
     * @param childDriName   子文件夹名
     * @return  子文件夹
     */
    public static File getOrCreateAppDir(String childDriName) {
        String root_path = getRootDri();
        if (root_path == null)
            return null;

        File dir = new File(root_path + childDriName);
        if (!dir.exists())
            dir.mkdirs();

        return dir;
    }

    /**
     * 获取内存卡，或者机身内存的根路径
     * @return
     *  如有内存卡返回内存卡根路径，
     *  否则返回机身内存的根路径
     */
    public static String getRootDri() {
        if (TextUtils.isEmpty(APP_FILE_SAVE_ROOT_DRI)) {    // 优先获取内置SD卡
            APP_FILE_SAVE_ROOT_DRI = getExternalStorageDirectory();
        }

        if (TextUtils.isEmpty(APP_FILE_SAVE_ROOT_DRI)) {    // 如果都没有，才使用机身内存
            APP_FILE_SAVE_ROOT_DRI = getInternalFileDirectory(MyApplication.getInstance());
        }

        return APP_FILE_SAVE_ROOT_DRI;
    }

    /**
     * 打开并安装APK文件
     */
    public static boolean installApkFile(File file) {
        Uri contentUri;
        if (file.exists() && file.length() > 0) {
            Intent installIntent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {   // API 24 以上

                installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                contentUri = FileProvider.getUriForFile(MyApplication.getInstance(), BuildConfig.APPLICATION_ID + ".file_provider", file);
                installIntent.setDataAndType(contentUri, "application/vnd.android.package-archive");

            } else {    // API 24 以下
                installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                contentUri = Uri.fromFile(file);
                installIntent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            }
            MyControl.getActivityManage().getCurrentActivity().startActivity(installIntent);
            return true;
        }

        return false;
    }

    /**
     * 创建文件
     * @param filePath  路径
     * @param fileName  文件名
     * @return 文件
     */
    public static File createNewFile(String filePath, String fileName)
            throws IOException {

        File folderFile = new File(filePath);

        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        File file = new File(filePath, fileName);
        if (file.exists()) {
            file.delete();
        }

        file.createNewFile();
        return file;
    }

    /**
     * 获取内置SD卡
     */
    private static String getExternalStorageDirectory() {
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (! sdCardExist) { // 不存在返回空
            return null;
        }

        String fileDirPath = Environment.getExternalStorageDirectory().getPath();

        return fileDirPath;
    }

    /**
     * 获取机身储存
     */
    private static String getInternalFileDirectory(Context context) {
        String fileDirPath = null;
        File fileDir = context.getFilesDir();
        if (fileDir != null) {
            fileDirPath = fileDir.getPath();
        }
        return fileDirPath;
    }
}
